<template>
<el-container class="el-container" direction="vertical">
  <el-row style="margin-top: 20px">
    <el-table
      border
      class="reset-input"
      :data="tableData"
      style="width: 100%;">
      <el-table-column
        prop="id"
        label="个人信息">
        <template slot-scope="scope">
          <el-row>
            <el-form label-position="'right'" label-width="150px" :model="form" :rules="rules" ref="profileForm">
              <el-form-item label="用户名">
                <div style="margin-left: 20px">
                  <span class="el-form-item-profile">{{form.username}}</span>
                </div>
              </el-form-item>
              <el-form-item label="电话号码" prop="phoneNumber">
                <el-input v-model="form.phoneNumber" class="el-form-item-profile"></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="form.gender" class="el-form-item-profile" style="margin-left: 25px">
                  <el-radio label="1">男</el-radio>
                  <el-radio label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="姓名" prop="name">
                <el-input v-model="form.name" class="el-form-item-profile"></el-input>
              </el-form-item>
              <el-form-item label="身份证号" prop="idNumber">
                <el-input v-model="form.idNumber" class="el-form-item-profile"></el-input>
              </el-form-item>
            </el-form>
          </el-row>
          <el-row>
            <el-col :span="2" :offset="19">
              <el-button type="primary" @click="saveProfile" size="small">保 存</el-button>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
  </el-row>
  <el-row style="margin-top: 20px">
    <el-table
      border
      :data="tableData"
      style="width: 100%">
      <el-table-column
        label="密码修改">
        <template slot-scope="scope">
          <el-row>
            <el-form label-position="'right'" label-width="150px" :model="pwdFrom" ref="pwdRef" :rules="pwdRules">
              <el-form-item label="新密码" prop="newPwd">
                <el-input type="password" v-model="pwdFrom.newPwd" class="el-form-item-profile"></el-input>
              </el-form-item>
              <el-form-item label="确认新密码" prop="ackPwd">
                <el-input type="password" v-model="pwdFrom.ackPwd" class="el-form-item-profile"></el-input>
              </el-form-item>
            </el-form>
          </el-row>
          <el-row>
            <el-col :span="2" :offset="19">
              <el-button type="primary" @click="savePwd" size="small">保 存</el-button>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
  </el-row>
  <el-dialog
    title="电话验证"
    :visible.sync="dialogVisible"
    width="30%"
    :before-close="handleClose">
    <el-input v-model="this.form.phoneNumber" disabled style="margin-bottom: 20px">
      <template slot="append">
        <el-button plain @click="sendYzm" v-if="!yzmDisabled">发送验证码</el-button>
        <el-button :disabled="yzmDisabled" v-if="yzmDisabled" plain>{{countDown}}秒后重新发送</el-button>
      </template>
    </el-input>
    <el-input placeholder="请输入验证码" v-model="code" clearable></el-input>
    <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="validateCode">确 定</el-button>
  </span>
  </el-dialog>
</el-container>
</template>

<script>
export default {
  name: 'Profile',
  created () {
    this.getProfile()
  },
  data () {
    let validateIdNumber = (rule, value, callback) => {
      let _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      let _IDre15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/
      // 校验身份证：
      if (_IDRe18.test(value) || _IDre15.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的身份证号'))
      }
    }
    let validatePhoneNumber = (rule, value, callback) => {
      let phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/
      if (phoneReg.test(value)) {
        callback()
        this.isFsyzm = true
      } else {
        callback(new Error('请输入正确的大陆手机号码！'))
        this.isFsyzm = false
      }
    }
    return {
      isFsyzm: false,
      yzmDisabled: false, // 按钮是否可用
      dialogVisible: false,
      code: '',
      countDown: 60, // 倒计时时间（单位：秒）
      rules: {
        phoneNumber: [
          {validator: validatePhoneNumber, required: true, trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入身份证姓名', trigger: 'blur'}
        ],
        idNumber: [
          {validator: validateIdNumber, required: true, trigger: 'blur'}
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ]
      },
      pwdRules: {
        newPwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' }
        ],
        ackPwd: [
          { required: true, message: '请确认新密码', trigger: 'blur' }
        ]
      },
      tableData: [{
        id: 1
      }],
      form: {
        username: '',
        phoneNumber: '',
        name: '',
        idNumber: '',
        gender: ''
      },
      prePhoneNumber: '',
      pwdFrom: {
        newPwd: '',
        ackPwd: ''
      }
    }
  },
  methods: {
    startCountDown () {
      this.yzmDisabled = true // 禁用按钮
      let timer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown--
        } else {
          clearInterval(timer)
          this.yzmDisabled = false // 启用按钮
          this.countDown = 60 // 重置倒计时时间
        }
      }, 1000)
    },
    sendYzm () {
      let _this = this
      if (this.isFsyzm) {
        this.$axios({
          url: '/api/sms',
          method: 'post',
          data: JSON.stringify({
            phoneNumber: _this.form.phoneNumber
          }),
          headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'token': _this.getToken()
          }
        }).then((response) => {
          if (response.data.code === 1) {
            _this.startCountDown()
          } else {
            _this.isTokenExpired(_this, response.data.msg)
            this.err(response.data.msg)
          }
        })
      } else {
        this.warn('请输入手机号码！')
      }
    },
    handleClose (done) {
      this.$confirm('确认取消电话验证？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    getProfile () {
      let _this = this
      this.$axios({
        url: '/api/users/' + _this.getUserID(),
        method: 'get',
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
          'token': _this.getToken()
        }
      }).then((response) => {
        if (response.data.code === 1) {
          let resData = response.data.data
          _this.form.username = resData.username
          _this.form.phoneNumber = resData.phoneNumber
          _this.prePhoneNumber = resData.phoneNumber
          _this.orPhoneNumber = resData.phoneNumber
          _this.form.name = resData.name
          _this.form.idNumber = _this.decryptEasy(resData.idNumber)
          _this.form.gender = resData.gender.toString()
        } else {
          _this.isTokenExpired(_this, response.data.msg)
          this.err(response.data.msg)
        }
      })
    },
    validateCode () {
      let _this = this
      this.$axios({
        url: '/api/sms/validate',
        method: 'post',
        data: JSON.stringify({
          code: _this.code,
          phoneNumber: _this.form.phoneNumber
        }),
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
          'token': _this.getToken()
        }
      }).then((response) => {
        if (response.data.code === 1) {
          _this.dialogVisible = false
          _this.prePhoneNumber = _this.form.phoneNumber
          _this.code = ''
          _this.success('电话号码验证成功！')
          _this.saveProfile()
        } else {
          _this.isTokenExpired(_this, response.data.msg)
          this.err(response.data.msg)
        }
      })
    },
    saveProfile () {
      if (this.orPhoneNumber !== this.form.phoneNumber && this.prePhoneNumber !== this.form.phoneNumber) {
        this.dialogVisible = true
        return
      }
      let _this = this
      let iv = _this.randomIv(16)
      this.$refs.profileForm.validate((valid) => {
        if (valid) {
          this.$axios({
            url: '/api/users',
            method: 'put',
            data: JSON.stringify({
              username: _this.form.username,
              phoneNumber: _this.form.phoneNumber,
              name: _this.form.name,
              idNumber: _this.encrypt(_this.form.idNumber, iv),
              gender: _this.form.gender,
              iv: iv,
              userID: _this.getUserID()
            }),
            headers: {
              'Content-Type': 'application/json; charset=utf-8',
              'token': _this.getToken()
            }
          }).then((response) => {
            if (response.data.code === 1) {
              this.success('个人信息保存成功！')
            } else {
              _this.isTokenExpired(_this, response.data.msg)
              this.err(response.data.msg)
            }
          })
        }
      })
    },
    savePwd () {
      let _this = this
      this.$refs.pwdRef.validate((valid) => {
        if (valid) {
          let iv = _this.randomIv(16)
          let pwdE = _this.encrypt(_this.pwdFrom.ackPwd, iv)
          _this.pwdFrom.newPwd = pwdE
          _this.pwdFrom.ackPwd = pwdE
          this.$axios({
            url: '/api/users/pwd',
            method: 'put',
            data: JSON.stringify({
              password: pwdE,
              iv: iv,
              userID: _this.getUserID()
            }),
            headers: {
              'Content-Type': 'application/json; charset=utf-8',
              'token': _this.getToken()
            }
          }).then((response) => {
            if (response.data.code === 1) {
              this.success('密码修改成功！')
              this.$router.push({path: '/login'})
            } else {
              _this.isTokenExpired(_this, response.data.msg)
              this.err(response.data.msg)
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
/* 修改表格悬停颜色 */
/deep/ .el-table--enable-row-hover .el-table__body tr:hover>td{
  background-color: transparent !important;
}
.el-container{
  width: 80%;
  margin: 0 auto;
}
.el-form-item-profile{
  margin-left: 10px;
  width: 800px;
}
</style>

<style scoped>
/deep/ .reset-input .el-input__inner{
  border: 1px #FFFFFF solid;
}
/deep/ .reset-input .el-input__inner:hover{
  border: 1px #FFFFFF solid;
}
/deep/ .reset-input .el-input__inner:focus{
  border-top: none;
  border-left: none;
  border-right: none;
  border-bottom: 1px var(--them-color) solid;
  border-radius: 0;
}
/deep/ .reset-input .el-form-item.is-error .el-input__inner, .el-form-item.is-error .el-input__inner:focus, .el-form-item.is-error .el-textarea__inner, .el-form-item.is-error .el-textarea__inner:focus{
  border-top: none;
  border-left: none;
  border-right: none;
  border-bottom: 1px var(--them-color) solid;
  border-radius: 0;
}
/deep/ .reset-input .el-form-item__error {
  margin-left: 20px;
}
</style>
